/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.cmd;

import com.je.bpm.common.operation.OperatorEnum;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.FlowElement;
import com.je.bpm.core.model.SequenceFlow;
import com.je.bpm.core.model.config.CustomEvent;
import com.je.bpm.core.model.event.StartEvent;
import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.ActivitiIllegalArgumentException;
import com.je.bpm.engine.ActivitiObjectNotFoundException;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.ExecutionEntity;
import com.je.bpm.engine.impl.persistence.entity.TaskEntity;
import com.je.bpm.engine.runtime.ProcessInstance;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * 撤销命令
 */
public class CancelProcessInstanceCmd extends NeedsActiveTaskCmd<Void> implements Serializable {

    private static final long serialVersionUID = 1L;
    protected String processInstanceId;
    protected String cancelReason;
    protected String businessKey;

    public CancelProcessInstanceCmd(String processInstanceId, String cancelReason, String businessKey, Map<String, Object> bean,
                                    String prod) {
        super(false, prod, bean);
        this.processInstanceId = processInstanceId;
        this.cancelReason = cancelReason;
        this.businessKey = businessKey;
    }

    @Override
    public Void execute(CommandContext commandContext, TaskEntity taskEntity) {
        if (processInstanceId == null) {
            throw new ActivitiIllegalArgumentException("processInstanceId is null");
        }

        ExecutionEntity processInstanceEntity = commandContext.getExecutionEntityManager().findById(processInstanceId);
        if (processInstanceEntity == null) {
            throw new ActivitiObjectNotFoundException("No process instance found for id '" + processInstanceId + "'", ProcessInstance.class);
        }

        BpmnModel bpmnModel = commandContext.getProcessEngineConfiguration().getRepositoryService().getBpmnModel(processInstanceEntity.getProcessDefinitionId());

        FlowElement firstNode = findFirstFlowElement(commandContext, processInstanceEntity.getProcessDefinitionId());

        List<TaskEntity> tasks = commandContext.getProcessEngineConfiguration().getTaskEntityManager().findTasksByProcessInstanceId(processInstanceId);
        if (tasks == null || tasks.size() > 1) {
            throw new ActivitiException("Can't cancel this process instance because of this process instance has multi tasks!");
        }
        commandContext.getHistoricProcessInstanceEntityManager().deleteHistoricProcessInstanceByBusinessKey(businessKey);
        if (tasks == null || tasks.size() < 1) {
            throw new ActivitiException("Can't cancel this process instance because of this process instance has no tasks!");
        }

        if (!tasks.get(0).getTaskDefinitionKey().equals(firstNode.getId())) {
            throw new ActivitiException("Only at the first task can cancel the process instance!");
        }
        commandContext.getExecutionEntityManager().deleteProcessInstance(processInstanceEntity.getProcessInstanceId(), cancelReason, false);
        //执行自定义流程节点策略
        commandContext.getProcessEngineConfiguration().getProcessInstanceHelper().invokeEvent
                (bpmnModel.getMainProcess().getCustomEventListeners(), tasks.get(0).getName(),
                        tasks.get(0).getBusinessKey(), "",
                        CustomEvent.CustomEventEnum.PROCESS_REVOKE, commandContext, "", taskId, OperatorEnum.PROCESS_CANCEL_OPERATOR);
        commandContext.getProcessEngineConfiguration().getProcessInstanceHelper().updateBeanInfo
                (bpmnModel.getMainProcess().getProcessConfig(), tasks.get(0).getBusinessKey(),
                        "NOSTATUS", commandContext);
        return null;
    }

    private FlowElement findFirstFlowElement(CommandContext commandContext, String processDefinitionId) {
        BpmnModel bpmnModel = commandContext.getProcessEngineConfiguration().getRepositoryService().getBpmnModel(processDefinitionId);
        FlowElement startElement = bpmnModel.getMainProcess().getInitialFlowElement();
        if (startElement == null) {
            throw new ActivitiException("Can't find the start element!");
        }
        StartEvent startEvent = (StartEvent) startElement;
        if (startEvent.getOutgoingFlows() == null || startEvent.getOutgoingFlows().size() < 1) {
            throw new ActivitiException("Can't find the outgoing from the start element!");
        }

        SequenceFlow sequenceFlow = startEvent.getOutgoingFlows().get(0);
        if (sequenceFlow == null) {
            throw new ActivitiException("Can't find the outgoing from the start element!");
        }
        String targetRef = sequenceFlow.getTargetRef();
        FlowElement firstNode = bpmnModel.getFlowElement(targetRef);
        if (firstNode == null) {
            throw new ActivitiException("Can't find the first element from the definition!");
        }
        return firstNode;
    }

}
